package myPetStore.web.servlet;

import myPetStore.domain.Account;
import myPetStore.domain.Category;
import myPetStore.domain.Log;
import myPetStore.domain.Product;
import myPetStore.persistence.LogDao;
import myPetStore.persistence.impl.LogDaoImpl;
import myPetStore.service.AccountService;
import myPetStore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

public class SignOnServlet extends HttpServlet {

    private String username;
    private String password;
    private String email;
    private String inputToken;//用户输入的
    private String verification;
    private String msg;
    private String from;//从哪个页面发来的请求
    private static final String  SIGN_ON_FORM="/WEB-INF/jsp/account/signon.jsp";
    private static final String  SIGN_ON_EMAIL_FORM="/WEB-INF/jsp/account/signonbyemail.jsp";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter();
        from=req.getParameter("login");

        if(from!=null&&!from.equals("")){
            if(from.equals("login")){
                loginByUsernameAndPassword(req, resp,out);
            }else if(from.equals("loginByEmail")){
                HttpSession session=req.getSession();
                verification=(String) session.getAttribute("verification");
                loginByEmailAndToke(req,resp,out);
            }
        }

        //简单校验用户输入的正确性

    }

    //通过邮箱和验证码登录
    private void loginByEmailAndToke(HttpServletRequest req, HttpServletResponse resp,PrintWriter out) throws ServletException, IOException {
        this.email=req.getParameter("email");
        this.inputToken=req.getParameter("token");
        if(!validate(2)){
            req.setAttribute("signonMsg",this.msg);
            req.setAttribute("inputEmail",this.email);
            req.setAttribute("token","");
            //TODO
            out.println(this.msg);
        }else {
            AccountService accountService=new AccountService();
            Account loginAccount=accountService.getAccountByEmail(this.email);
            if(loginAccount==null){
                this.msg="The email address does not exist, please register first";
                req.setAttribute("inputEmail","");
                out.println(this.msg);
            }else{
                //判断验证码对错
                if(!verification.equals(inputToken)){
                    this.msg="The verification code is incorrect, please re-enter it";
                    req.setAttribute("signonMsg",this.msg);
                    req.setAttribute("inputEmail",email);
                    out.println(this.msg);
                }else{
                    HttpSession session=req.getSession();
                    session.setAttribute("loginAccount",loginAccount);
                    if(loginAccount.isListOption()){
                        CatalogService catalogService=new CatalogService();
                        List<Product> productList=catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                        session.setAttribute("myList",productList);
                    }
                    out.println("address:mainForm");
                    Log log = new Log();
                    log.setLogTime(new Date());
                    log.setUserName(username);
                    log.setTitle("登录信息");
                    log.setContent("用户" + username + "登录了账号");
                    LogDao logDao = new LogDaoImpl();
                    logDao.InsertLog(log);
                }
            }
        }
    }
    //通过用户名和密码登录
    private void loginByUsernameAndPassword(HttpServletRequest req, HttpServletResponse resp,PrintWriter out) throws ServletException, IOException {
        this.username=req.getParameter("username");
        this.password=req.getParameter("password");

        if(!validate(1)){
            req.setAttribute("signonMsg",this.msg);
            //TODO
            out.println(this.msg);
        }else{
            AccountService accountService=new AccountService();
            Account loginAccount=accountService.getAccount(this.username,this.password);
            if(loginAccount==null){
                this.msg="The username or the password is wrong";
                req.setAttribute("signonMsg",this.msg);
                //TODO
                out.println(this.msg);
            }else{
//                loginAccount.setPassword(null);
                HttpSession session=req.getSession();
                session.setAttribute("loginAccount",loginAccount);
                if(loginAccount.isListOption()){
                    CatalogService catalogService=new CatalogService();
                    List<Product> productList=catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList",productList);
                }
                //
                out.println("address:mainForm");
                Log log = new Log();
                log.setLogTime(new Date());
                log.setUserName(username);
                log.setTitle("登录信息");
                log.setContent("用户" + username + "登录了账号");
                LogDao logDao = new LogDaoImpl();
                logDao.InsertLog(log);
            }
        }
    }
    private boolean validate(int flag){
        //1为密码登录界面，2为邮箱登录界面
        switch (flag){
            case 1: {
                if(this.username==null||username.equals("")){
                    this.msg="The username cannot be empty";
                    return false;
                }
                if (this.password==null||password.equals("")){
                    this.msg="The password cannot be empty";
                    return false;
                }
                break;
            }
            case 2: {
                if(this.email==null||email.equals("")){
                    this.msg="The email cannot be empty";
                    return false;
                }
                if (this.inputToken==null||inputToken.equals("")){
                    this.msg="The token cannot be empty";
                    return false;
                }
                break;
            }
        }
        return true;
    }
}
